package www.dianbaozu.com.ui.login

import androidx.databinding.ObservableField
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import www.dianbaozu.com.R
import www.dianbaozu.com.extension.nimFlow
import www.dianbaozu.com.extension.save
import www.wen.com.common.lib.base.module.BaseApiViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.data.repository.AppDataManager
import www.wen.com.common.lib.extension.getString
import www.wen.com.common.lib.util.SpUtil


/**
 * @author WEN
 * @Description:
 * @date 2021/9/1 10:32
 */

class LoginViewModel @ViewModelInject constructor(appDataManager: AppDataManager) : BaseApiViewModel(appDataManager) {

    val mEnableLogin = ObservableField(true)

    val mPassword = ObservableField("")

    val mPhone = ObservableField("")

    val mAgree = ObservableField(false)

    var mLoginInfo:LoginInfo? = null

    /**
     * 验证码注册|登陆
     */
    @FlowPreview
    fun requestRegister(
            requestRegisterBody: RequestRegisterBody,
            action: (LoginInfo) -> Unit,
    ) {
        viewModelScope.launch {
            mLoginInfo = null
            appDataManager.loginOrRegisterFlow("login", requestRegisterBody)
                    .retryWhen { cause, attempt ->
                        return@retryWhen cause.message == "网络异常" && attempt <= 1
                    }
                    .flatMapConcat {
                        mLoginInfo = it.data

                        if(!it.data.user.forbidStatus){
                            appDataManager.nimFlow(
                                    it.data.user.accId,
                                    it.data.user.accToken
                            ) {
                                SpUtil.save(it.data.user)
                                SpUtil.save(it.data.token!!)
                            }
                        }else{
                            throw Exception("账号被封禁")
                        }
                    }
                    .onStart {
                        loading.value = UiStateCustom(
                                stateData = LoadingDialog(
                                        getString(R.string.logging_in),
                                        LoadingDialogStateType.LOADING
                                )
                        )
                    }
                    .onCompletion { cause ->
                        if (cause == null) {
                            loading.value = UiStateCustom(
                                    stateData = LoadingDialog(
                                            tip = getString(R.string.successful_landing),
                                            loadingDialogStateType = LoadingDialogStateType.SUCCESS,
                                            isShowDialogTip = false,
                                            isShowToastTip = true
                                    )
                            )
                        }
                    }
                    .catch { cause ->
                        loading.value = UiStateCustom(
                                stateData = LoadingDialog(
                                        tip = cause.message ?: "网络异常",
                                        loadingDialogStateType = LoadingDialogStateType.ERROR,
                                        isShowDialogTip = false,
                                        isShowToastTip = (cause.message != null && cause.message != "账号被封禁"),
                                        action = { mLoginInfo?.run { action.invoke(mLoginInfo!!) } }
                                )
                        )
                    }
                    .collect {
                        mLoginInfo?.run { action.invoke(mLoginInfo!!) }
                    }
        }
    }


    fun onPasswordOrPhoneTextChanged() {
        mEnableLogin.set(enableLogin())
    }

    fun enableLogin(): Boolean {
//        return (mPhone.get()!!.isNotBlank() &&
//                mPhone.get()!!.length >= 5 &&
//                mPassword.get()!!.isNotBlank() &&
//                mPassword.get()!!.length >= 6 &&
//                mAgree.get()!!)
        return true
    }

}